#include <iostream>
#include <cstring>
#include <fstream>
#include "Server.h"
#include "FUNCTIONS.h"
#include "RedisCli.h"
extern"C"{
#include "../element/syncd/include/sln_nlink.h"
#include "../element/syncd/include/sln_syncd.h"
#include "../element/sln/include/sln_add.h"
}
#include "CallBack.h"

std::string SERVER_IP;
std::string GUANLIAN_IP;
std::string RENZHENG_IP;
std::string HOST_NAME;
int SEND_ROUTER_INFO;


int main() {

	//test_publish
	// Json::Value src_;
	// src_["rid"] = "12345678912345678912345678900000";
	// src_["mac"] = "aa:bb:cc:dd:ee:ff";
	// src_["ifn"] = "Ethernet4";
	// src_["pktid"] = 0;
	// src_["multicast"] = 0;
	// src_["cache"] = 0;
	// src_["check"] = 0;
	// std::string cid = "12345678900987654321123456789012";
	// Json::StreamWriterBuilder writer;
	// writer["indentation"] = "";
	// std::string src_str = Json::writeString(writer, src_);
	// RedisCli::HSET_val("SLN_CID_TABLE", cid, src_str);
	// std::cout << "已下发" << std::endl;



	// 打开配置文件
    std::ifstream configFile("config.json");

    if (!configFile.is_open()) {
        std::cerr << "Failed to open config file." << std::endl;
        return 1;
    }
    // 解析JSON配置文件
    Json::Value content;
    Json::CharReaderBuilder reader;
    std::string errs;

    if (!Json::parseFromStream(reader, configFile, &content, &errs)) {
        std::cerr << "Failed to parse config file: " << errs << std::endl;
        return 1;
    }
    // 读取配置信息并赋值给全局变量
    SERVER_IP = content["SERVER_IP"].asString();
	GUANLIAN_IP = content["GUANLIAN_IP"].asString();
	RENZHENG_IP = content["RENZHENG_IP"].asString();
	HOST_NAME 	= content["HOST_NAME"].asString();
	SEND_ROUTER_INFO = content["SEND_ROUTER_INFO"].asInt();
	std::cout << "读取配置文件成功！" << SERVER_IP << GUANLIAN_IP << RENZHENG_IP << std::endl;
	configFile.close();

	if(!SEND_ROUTER_INFO){
		Functions::send_router_addr();
		content["SEND_ROUTER_INFO"] = 1;
		std::ofstream output("config.json");
		output << std::setw(4) << content <<std::endl;
		output.close();
	}




	std::thread thread1(&Server::ListenAndStore);
	std::thread thread2(&Server::ListenCidBackRid);
	std::thread thread3(&Server::Connect);
	std::thread thread4(&Server::Recept);
	std::thread thread5(&RedisCli::WATCH, "SLN_CID_EVENT_TABLE");
	std::thread thread6(&Server::Delete);
	
	//std::thread thread3(&Server::ListenRidBackCid);
	//std::thread thread4(&Server::ListenCidBackMid);
	//std::thread thread5(&Server::ListenRidBackMid);
	//std::thread thread6(&cycle);

	//test 记得以后创建线程后台调用
	// std::thread thread6(&Functions::send_router_addr);
	// thread6.detach();

	thread1.join();
	thread2.join();
	thread3.join();
	thread4.join();
	thread5.join();
	thread6.join();
	std::cout << "标识app程序已退出" << std::endl;
	return 0;
}